import type { Metadata as MetadataNext } from 'next';
import { createError, getMetadata } from '@/lib/tool';
import { authMiddleware } from '@/lib/api';
import { cookies } from 'next/headers';
import { queryAllSection, queryPath } from '@/services/api';
import type { IPagination, IPath, ISection } from '@/interfaces';
import ResetPage from '@/app/[locale]/reset/reset';
import SectionAdminPage from '@/app/[locale]/admin/forum/section/section';
import { getTranslator } from 'next-intl/server';
import { getTranslatedFields } from '@/lib/dictionaries';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = await getTranslator(locale);
  return getMetadata({ title: t('sectionAdminPage.title.section') });
}

async function getData() {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = queryAllSection({
      baseURL: process.env.APP_API_SERVER,
      token,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    return {
      isSuccess: true,
      isError: false,
      path: resp1.data as IPath,
      info: resp2.data as IPagination<ISection>,
    };
  } catch (e: any) {
    return {
      isSuccess: false,
      isError: true,
      error: e,
    };
  }
}

export default async function Page({
  params: { locale },
}: {
  params: { locale: string };
}) {
  const data = await getData();
  if (data.isError) {
    return <ResetPage error={createError(data.error)} />;
  }

  const source = data.info!;
  const translatedFields = await getTranslatedFields(
    locale,
    'sectionAdminPage',
  );

  return (
    <SectionAdminPage source={source} translatedFields={translatedFields} />
  );
}
